import { ref } from 'vue'
import { defineStore } from 'pinia'

export const useAuthStore = defineStore(
  'auth',
  () => {
    // 定义数据
    const auth = ref({
      authority: null,
      token: ''
    })

    // 接口初始化数据
    const initAuth = ({ authority, token }) => {
      auth.value = {
        authority: authority,
        token: token
      }
    }

    // 检验数据 调用方式：verifyAuth()
    const verifyAuth = () => {
      // 数据为空 --> 检查本地数据
      if (auth.value.authority === null || auth.value.token == '') {
        const local = localStorage.getItem('auth')
        // 本地数据为空 --> 未登录，数据不存在 --> 返回False
        if (local === null || local === '' || local === undefined) return false
        // 本地数据不为空 --> 检验数据 --> 数据格式异常 --> 返回False
        const localData = JSON.parse(local)
        if (
          localData.authority === undefined ||
          localData.token === undefined ||
          localData.authority === null ||
          localData.token === null ||
          localData.authority === '' ||
          localData.token === ''
        )
          return false
        // 数据格式正确 --> 重新赋值 --> 返回ture
        initAuth(localData)
        return true
      }
      // 数据不为空 --> 返回true
      return true
    }

    // 清除数据
    const clearAuth = () => {
      auth.value.authority = null
      auth.value.token = ''
      if (localStorage.getItem('auth')) localStorage.removeItem('auth')
    }

    // return
    return {
      auth,
      initAuth,
      verifyAuth,
      clearAuth
    }
  },
  {
    persist: true
  }
)
